package xian.woniuxy.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xian.woniuxy.entity.Role;
import xian.woniuxy.entity.User;
import xian.woniuxy.mapper.UserMapper;
import xian.woniuxy.mapper.custom.CustomRoleMapper;
import xian.woniuxy.mapper.custom.CustomUserMapper;
import xian.woniuxy.service.RoleService;
import xian.woniuxy.service.UserService;

import java.util.List;

/**
 * @author gao
 * @date 2023/07/03 11:30:53
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private CustomUserMapper userMapper;

    @Autowired
    private RoleService roleService;

    @Override
    public int save(User user) {
        return userMapper.insertSelective(user);
    }

    @Override
    public int delete(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(User user) {
        return userMapper.updateByPrimaryKey(user);
    }

    @Override
    public User findOne(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        List<Role> roles = roleService.findByUserId(id);
        user.setRoles(roles);
        return user;
    }

    @Override
    public List<User> findAll() {
        return userMapper.selectByExample(null);
    }

    @Override
    public int distributeUserRoles(Integer userId, List<Integer> roleIds) {
        int rows = userMapper.clearUserRoles(userId);
        if(roleIds.size() > 0) {
            rows += userMapper.distributeUserRoles(userId, roleIds);
        }
        return rows;
    }

}
